
#include "ChessModel.h"
#include <cstring>
#include <XMLScribe.h>


//! Constructor
ChessModel::ChessModel(){
   Initialize();
}

void ChessModel::Initialize() {
   myBoard = new Board();
   history = new MoveHistory();
}

ChessModel::~ChessModel() {
   Destroy();
}

void ChessModel::Destroy() {
   delete myBoard;
   delete history;

   myBoard = NULL;
   history = NULL;

   for (int i=offBoardPieces.size()-1; i >-1; i--) {
      delete offBoardPieces[i];
   }

   offBoardPieces.clear();
}

bool ChessModel::AddPiece(BoardPosition pos, Piece * curPiece) {
   return myBoard->AddPiece(pos, curPiece);
}

Piece * ChessModel::RemovePiece(BoardPosition pos) {
   return myBoard->RemovePiece(pos);
}

/**
   * Indicate to the player that the user clicked on the given
   * row and column with the mouse.
   */
Piece * ChessModel::on_CellSelected(BoardPosition pos, int button){
   return pos.GetRow() != -1 ? myBoard->GetPiece(pos) : NULL;
}

/**
   * Handle when the user selected the new game button.
   */
void ChessModel::on_NewGame(){
   Destroy();

   Initialize();
}

/**
   * Handle when the user selected the save game button.
   */
void ChessModel::on_SaveGame(){
   XMLScribe(myBoard, history);
}

/**
   * Handle when the user selected the save game as button.
   */
void ChessModel::on_SaveGameAs(std::string filename){
   XMLScribe(myBoard, history, filename.c_str());
}

/**
   * Handle when the user selected the load game button.
   */
void ChessModel::on_LoadGame(std::string filename){

   HTMLParser * parser = new HTMLParser(filename);

   delete parser;
}

/**
   * Handle when the user selected the undo move button.
   */
Move ChessModel::on_UndoMove() {
   Move m = history->UndoMove();

   // Case: No moves made
   if (m.GetStartPos().GetRow() <0)
      return m;

   myBoard->AddPiece(m.GetStartPos(), m.GetMovedPiece());
   myBoard->AddPiece(m.GetEndPos(), m.GetTakenPiece());

   if (m.GetTakenPiece() != NULL)
      offBoardPieces.pop_back();

   return m;
}

Piece * ChessModel::GetPiece(BoardPosition pos) {
   return myBoard->GetPiece(pos);
}

Board * ChessModel::GetBoard() {
   return myBoard;
}
